<template>
  <van-nav-bar :border="false" class="navBar">
    <template #title>
      <div class="navBarTitle">舟山触点助手</div>
    </template>
  </van-nav-bar>
  <div class="fatherContainer">
    <div class="contentWord">手机号快捷登录</div>
    <div style="height: 60px"></div>
    <van-form @submit="onSubmit" style="width: 100%">
      <van-field
        class="inputBox"
        v-model="loginForm.phone"
        name="username"
        placeholder="请输入手机号"
        :rules="[
          { required: true, message: '请输入手机号' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' }
        ]"
      >
        <template #label>
          <img class="usernameIcon" src="@/assets/username.png" />
        </template>
      </van-field>
      <div style="height: 20px"></div>
      <van-field
        class="inputBox"
        v-model="loginForm.code"
        name="code"
        placeholder="请输入短信验证码"
        :rules="[
          { required: true, message: '请输入短信验证码' },
          { pattern: /^[0-9]{6}$/, message: '验证码必须是六位数字' }
        ]"
      >
        <template #label>
          <img class="codeIcon" src="@/assets/code.png" />
        </template>
        <template #extra>
          <div class="codeWord" @click="getCodeButton" v-if="codeStatus == 0">获取验证码</div>
          <van-loading v-else-if="codeStatus == 1" size="18" type="spinner" color="#1989fa" />
          <div class="codeWord" v-else-if="codeStatus == 2">{{ counter }}秒后重新获取</div>
        </template>
      </van-field>
      <div style="height: 40px"></div>
      <van-button
        class="submitButton"
        :loading="isLoading"
        block
        type="primary"
        native-type="submit"
        loading-text="登录中..."
      >
        登录
      </van-button>
    </van-form>
  </div>
</template>

<script setup>
import { ref, onBeforeUnmount, onMounted } from 'vue'
import { showFailToast } from 'vant'
import { getCode, login, validateJWT } from '@/api/login/index.js'
// import useuserStore from "@/store/modules/user";
import { useRouter } from 'vue-router'

onMounted(async () => {
  const jwt = localStorage.getItem('jwt')
  console.log('jwt')
  if (jwt !== null) {
    console.log('mounted')
    const response = await validateJWT(jwt)
    console.log(response)
    if (response.data.code == 200) {
      router.push('/home')
    } else {
      //清楚localStorage
      localStorage.removeItem('jwt')
      localStorage.removeItem('phone')
    }
  }
})
//获取当前应用的路由实例
let router = useRouter()

//登录按钮的加载状态
let isLoading = ref(false)
//是否可获取验证码.0:可获取，1:正在获取，2:不可获取
let codeStatus = ref(0)
const counter = ref(60)

const loginForm = ref({
  phone: '',
  code: ''
})

const getCodeButton = () => {
  // 手机号验证逻辑
  const phoneRegex = /^1[3-9]\d{9}$/ // 中国手机号正则表达式
  if (!loginForm.value.phone) {
    showFailToast('请输入手机号')
    return
  } else if (!phoneRegex.test(loginForm.value.phone)) {
    showFailToast('请输入有效的手机号')
    return
  } else {
    //获取验证码
    handleCode()
  }
}

const handleCode = async () => {
  try {
    codeStatus.value = 1
    const response = await getCode(loginForm.value.phone)
    codeStatus.value = 2 //无论获取成功与否，都进入不可获取状态并倒计时，避免用户多次点击按钮
    startCountdown()
    console.log(response)
  } catch (e) {
    showFailToast(`网络异常,
  请重试!`)
    codeStatus.value = 2
  }
}

// 使用onBeforeUnmount来注册清理函数
const cleanup = () => {
  if (intervalId.value) {
    clearInterval(intervalId.value)
  }
}
onBeforeUnmount(cleanup)

// 如果intervalId是ref，则确保其定义也在顶层
const intervalId = ref()

function startCountdown() {
  intervalId.value = setInterval(() => {
    if (counter.value > 0) {
      counter.value--
    } else {
      clearInterval(intervalId.value)
      codeStatus.value = 0
      counter.value = 60 // 重置计数器
    }
  }, 1000)
}

const onSubmit = async () => {
  isLoading.value = true
  const response = await login(loginForm.value.phone, loginForm.value.code) //登录
  if (response.data.code == 200) {
    localStorage.setItem('jwt', response.data.data.jwt)
    localStorage.setItem('phone', loginForm.value.phone)
    router.push('/home')
  } else if (response.data.code == 400) {
    showFailToast(response.data.msg)
  }
  isLoading.value = false
}
</script>

<style scoped lang="scss">
.navBar {
  margin-top: 8px;
}

.navBarTitle {
  font-size: 18px;
  color: #000000;
  font-weight: normal;
}

.fatherContainer {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: calc(100% - 64px);
  margin-left: 32px;

  .contentWord {
    margin-top: 35px;
    font-size: 24px;
    color: #333333;
  }

  .inputBox {
    width: 100%;
    background: #f8f6fb;
    border-radius: 8px 8px 8px 8px;
  }

  .usernameIcon {
    margin-top: 4px;
    width: 12px;
    height: 16px;
  }

  .codeIcon {
    margin-top: 4px;
    width: 17px;
    height: 16px;
  }

  :deep(.van-field__label) {
    width: 16px;
    display: flex;
    align-items: flex-start;
  }

  :deep(.van-field__control) {
    margin-right: 10px;
  }

  :deep(.van-field__value) {
    display: flex;
    flex-direction: column;
  }

  .codeWord {
    color: #2973ff;
    cursor: pointer;
  }

  .submitButton {
    width: 100%;
    height: 44px;
    border-radius: 8px 8px 8px 8px;
  }
}
</style>
